package com.icss.struct.dao;

import com.icss.struct.dto.UserInfo;

import java.sql.*;
import java.util.HashMap;

public class UserDao {
    public UserInfo findUserInfoByUsername(String username) {
        UserInfo ui = null;
        // 2. 创建链接
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest?characterEncoding=utf8", "root", "root");

            // 3. 创建执行器：
            String sql = "SELECT t1.id, t1.uname, t1.nickname, t1.image, t1.price, t1.password, t1.ldate\n" +
                    "FROM sns_user t1\n" +
                    "WHERE t1.uname = ? ";

            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);

            // 4. 执行SQl,处理结果
            ResultSet rs = ps.executeQuery();

            // 处理结果集
            while (rs.next()) { // 有下一条记录并且指向这一行
                ui = new UserInfo();
                ui.setId(rs.getInt(1));
                ui.setUname(rs.getString(2));
                ui.setNickname(rs.getString(3));
                ui.setImage(rs.getString(4));
                ui.setPrice(rs.getInt(5));
                ui.setPassword(rs.getString(6));
                ui.setLdate(rs.getTimestamp(7));
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            // 5. 关闭资源
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return ui;

    }

    public void  addUser(HashMap<String, String> params) {
        // 2. 创建链接
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest?characterEncoding=utf8", "root", "root");
            conn.setAutoCommit(false);
            // 3. 创建执行器：
            String sql = "INSERT  INTO sns_user \n" +
                    "(uname,nickname,password) \n" +
                    "VALUES \n" +
                    "(?,?,?)";

            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, params.get("username"));
            ps.setString(2, params.get("nickname"));
            ps.setString(3,  params.get("password"));

            // 4. 执行SQl,处理结果
            int r = ps.executeUpdate();
            if (r == 1) {
                conn.commit();
            } else {
                conn.rollback();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
         } finally {
            // 5. 关闭资源
            try {
                assert conn != null;
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
